package com.redxiii.tracplus.web.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.jar.JarFile;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author dfilgueiras
 * TODO: Improve this code.
 */
public class ManifestReader {

	private static final Logger logger = LoggerFactory.getLogger(ManifestReader.class);
	
	public Configuration getManifestProperties() {
		try {
			try {
				ProtectionDomain domain = ManifestReader.class.getProtectionDomain();
				if (domain != null) {
					CodeSource codeSource = domain.getCodeSource();
					if (codeSource != null) {
						String location = codeSource.getLocation().toExternalForm();
						logger.info("SourceLocation: {}", location);
						
						int earFolderIndex = location.indexOf("/", location.indexOf(".ear"));
						
						String earFolder = location.substring(0, earFolderIndex);
						logger.info("earFolder: {}", earFolder);
						
						URL url = new URL(earFolder + "/" + JarFile.MANIFEST_NAME);
						if (url != null) {
							logger.info("Reading manifest file '{}' from ProtectionDomain", url);
							return new PropertiesConfiguration(url);
						}
					}
				}
			} catch (MalformedURLException e) {
				logger.error("Unable to read manifest file and get build revision",e);
			}
		} catch (ConfigurationException e) {
			logger.error("Unable to read manifest file and get build revision",e);
		}
		return null;
	}
}
